package com.ruoyi.gpt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.model.WxGptUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.gpt.domain.GptUser;
import com.ruoyi.gpt.mapper.GptUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.gpt.domain.bo.WxMsgBo;
import com.ruoyi.gpt.domain.vo.WxMsgVo;
import com.ruoyi.gpt.domain.WxMsg;
import com.ruoyi.gpt.mapper.WxMsgMapper;
import com.ruoyi.gpt.service.IWxMsgService;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 微信消息Service业务层处理
 *
 * @author ztx
 * @date 2023-03-17
 */
@RequiredArgsConstructor
@Service
public class WxMsgServiceImpl implements IWxMsgService {

    private final WxMsgMapper baseMapper;
    private final GptUserMapper gptUserMapper;

    /**
     * 查询微信消息
     */
    @Override
    public WxMsgVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询微信消息列表
     */
    @Override
    public TableDataInfo<WxMsgVo> queryPageList(WxMsgBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<WxMsg> lqw = buildQueryWrapper(bo);
        Page<WxMsgVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<WxMsgVo> queryPageListByGptUser(WxMsgBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<WxMsg> lqw = buildQueryWrapperGroupByGptUser(bo);
        Page<WxMsgVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<GptUser> gptUserList = gptUserMapper.selectList();
        // 根据WxMsgVo里面的id 找出gptUserList里面对应的gptUser并设置到WxMsgVo里面
        result.getRecords().forEach(wxMsgVo -> {
            gptUserList.forEach(gptUser -> {
                if (gptUser.getId().equals(wxMsgVo.getUserId())) {
                    wxMsgVo.setNickname(gptUser.getNickname());
                    wxMsgVo.setAvatar(gptUser.getAvatar());
                    wxMsgVo.setAppid(gptUser.getAppid());
                }
            });
        });
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<WxMsg> queryDetailPageList(WxMsgBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<WxMsg> lqw = buildQueryWrapper(bo);
        Page<WxMsg> result = baseMapper.selectPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询微信消息列表
     */
    @Override
    public List<WxMsgVo> queryList(WxMsgBo bo) {
        LambdaQueryWrapper<WxMsg> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<WxMsg> buildQueryWrapper(WxMsgBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<WxMsg> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getAppid()), WxMsg::getAppid, bo.getAppid());
        lqw.eq(StringUtils.isNotBlank(bo.getOpenid()), WxMsg::getOpenid, bo.getOpenid());
        lqw.eq(StringUtils.isNotBlank(bo.getInOut()), WxMsg::getInOut, bo.getInOut());
        lqw.eq(ObjectUtil.isNotNull(bo.getUserId()), WxMsg::getUserId, bo.getUserId());
        return lqw;
    }
    private LambdaQueryWrapper<WxMsg> buildQueryWrapperGroupByGptUser(WxMsgBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<WxMsg> lqw = Wrappers.lambdaQuery();
        lqw.select(WxMsg::getUserId); // 只查询用户id

        lqw.groupBy(WxMsg::getUserId); // 以用户id分组
        return lqw;
    }

    /**
     * 新增微信消息
     */
    @Override
    public Boolean insertByBo(WxMsgBo bo) {
        WxMsg add = BeanUtil.toBean(bo, WxMsg.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public void insertByBoAsync(WxMsgBo bo) {
        WxMsg add = BeanUtil.toBean(bo, WxMsg.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
    }

    /**
     * 修改微信消息
     */
    @Override
    public Boolean updateByBo(WxMsgBo bo) {
        WxMsg update = BeanUtil.toBean(bo, WxMsg.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(WxMsg entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除微信消息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<WxMsgVo> queryBackAndForthMsgList(Long userId) {
        //查找近10条对话
        LambdaQueryWrapper<WxMsg> qw = Wrappers.lambdaQuery();
        qw.eq(WxMsg::getUserId,userId); // 获取本人发送的对话
        qw.eq(WxMsg::getInOut,"2"); // 获取本人发送的对话，记录李包含对话的回复
        qw.isNotNull(WxMsg::getDetail); // 问题不为空
        qw.isNotNull(WxMsg::getRepContent); // 回复不为空
        qw.gt(WxMsg::getCreateTime, LocalDateTime.now().minusMinutes(5)); // 5分钟之内
        qw.orderByDesc(WxMsg::getCreateTime); // 时间倒叙
        qw.last("limit 0,3"); //last用法：在sql末尾添加sql语句，有sql注入风险
        return baseMapper.selectVoList(qw);
    }
}
